package com.jus.player.fragment.main;

import static com.jus.player.api.OkHttpHelper._DATA;
import static com.jus.player.util.CommonUtils.navigateTo;

import android.view.View;
import android.widget.LinearLayout;

import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.android.material.tabs.TabLayout;
import com.jus.player.R;
import com.jus.player.activity.home.JsPlayerActivity;
import com.jus.player.activity.home.SearchActivity;
import com.jus.player.adapter.play.CustomBannerAdapter;
import com.jus.player.adapter.play.PlayListAdapter;
import com.jus.player.api.ApiConfig;
import com.jus.player.api.OkHttpHelper;
import com.jus.player.entity.BannerEntity;
import com.jus.player.fragment.BaseFragment;
import com.jus.player.fragment.play.VideoListFragment;
import com.jus.player.util.CommonUtils;
import com.jus.player.util.LanguageUtils;
import com.youth.banner.Banner;
import com.youth.banner.config.BannerConfig;
import com.youth.banner.config.IndicatorConfig;
import com.youth.banner.indicator.CircleIndicator;
import com.youth.banner.util.BannerUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 放映列表页片段
 */
public class PlayListFragment extends BaseFragment {

    private final List<String> mTitles = new ArrayList<>(); //AppConfig.VIDEO_TYPE;
    private final List<Fragment> mFragments = new ArrayList<>();
    //轮播图数据
    private final List<BannerEntity> bannerList = new ArrayList<>();
    /**
     * 放映也tab容器viewPager
     */
    public ViewPager viewPager;
    public LinearLayout searchBtn;
    private PlayListAdapter playListAdapter;
    private CustomBannerAdapter bannerAdapter;

    public static PlayListFragment newInstance() {
        return new PlayListFragment();
    }

    @Override
    protected int initLayout() {
        return R.layout.fragment_play_list;
    }

    @Override
    protected void initView() {
        playListAdapter = new PlayListAdapter(getChildFragmentManager());
        playListAdapter.setFragments(mFragments);
        playListAdapter.setTitles(mTitles);

        viewPager = findViewById(R.id.play_list_view_pager);
        searchBtn = findViewById(R.id.search_linear_layout);
        searchBtn.setOnClickListener(view -> navigateTo(requireActivity(), SearchActivity.class));
        viewPager.setAdapter(playListAdapter);
        TabLayout tabLayout = findViewById(R.id.list_tab_layout);
        tabLayout.setupWithViewPager(viewPager);

        Banner<BannerEntity, CustomBannerAdapter> banner = findViewById(R.id.banner);
        bannerAdapter = new CustomBannerAdapter(bannerList);
        banner.setAdapter(bannerAdapter);
//        banner.setIndicator(new RoundLinesIndicator(requireActivity()));
//        banner.setIndicatorSelectedWidth(BannerUtils.dp2px(15));、
        banner.setIndicator(new CircleIndicator(getActivity()));
        banner.setIndicatorGravity(IndicatorConfig.Direction.RIGHT);
        banner.setIndicatorMargins(new IndicatorConfig.Margins(0, 0,
                BannerConfig.INDICATOR_MARGIN, BannerUtils.dp2px(12)));
        banner.setIndicatorNormalColor(ContextCompat.getColor(requireContext(), R.color.white));
        banner.setIndicatorSelectedColor(ContextCompat.getColor(requireContext(), R.color.app_theme_red));
        banner.setLoopTime(4000);
        //预加载fragment页面，避免下标越界问题
        //viewPager.setOffscreenPageLimit(mTitles.size());
        banner.setOnBannerListener((b, i) ->
                JsPlayerActivity.start(getActivity(), 0, b.id, false));
    }

    @Override
    protected void initData() {
        //初始化滑动tab数据
        getCategoryList();
    }

    @Override
    protected boolean isLazyLoad() {
        return true;
    }

    @Override
    public void onPause() {
        super.onPause();
        if (getActivity() != null) {
            getActivity().getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            );
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getActivity() != null) {
            getActivity().getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
            );
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            onPause();
        } else {
            onResume();
        }
    }

    private void getCategoryList() {
        String language = LanguageUtils.getCurrentLanguage(requireContext());
        Map<String, String> map = new HashMap<>();
        OkHttpHelper.getInstance(requireActivity()).getAsync(ApiConfig.CATEGORY_LIST, map,
                new OkHttpHelper.HttpCallback() {
                    @Override
                    public void onSuccess(String response) {
                        JSONObject categoryVo = JSONObject.parseObject(response).getJSONObject(_DATA);
                        JSONArray banners = categoryVo.getJSONArray("banners");
                        for (int i = 0; i < banners.size(); i++) {
                            JSONObject b = banners.getJSONObject(i);
                            BannerEntity bannerEntity = new BannerEntity(
                                    b.getString("url"), b.getString("description"), 1);
                            bannerEntity.id = b.getLong("id");
                            bannerList.add(bannerEntity);
                        }
                        JSONArray ja = categoryVo.getJSONArray("categoryList");
                        categoryVo.getJSONArray("banners");
                        if (ja == null || ja.isEmpty()) {
                            CommonUtils.showToastAsync(requireActivity(), requireActivity().getString(R.string.empty_state_message));
                            return;
                        }
                        if (getActivity() != null) {
                            getActivity().runOnUiThread(() -> {
                                bannerAdapter.updateData(bannerList);
                                for (int i = 0; i < ja.size(); i++) {
                                    JSONObject category = ja.getJSONObject(i);
                                    if (LanguageUtils.ZH_TW.equals(language)) {
                                        mTitles.add(category.getString("tcCategory"));
                                    } else if (LanguageUtils.EN.equals(language)) {
                                        mTitles.add(category.getString("enCategory"));
                                    } else {
                                        mTitles.add(category.getString("category"));
                                    }
                                    //初始化不同tab的页面
                                    mFragments.add(VideoListFragment.newInstance(category.getLong("id")));
                                }
                                playListAdapter.notifyDataSetChanged();
                            });
                        }
                    }

                    @Override
                    public void onFailure(OkHttpHelper.HttpException e) {
                        CommonUtils.showToastAsync(requireActivity(), e.getMessage());
                    }
                });
    }

}